package cn.com.api.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.com.api.entity.ApiT_delivery_account_state;
import cn.com.api.entity.ApiT_shipper_account;
import cn.com.api.mapper.ApiT_delivery_account_stateMapper;
import cn.com.api.mapper.ApiT_shipper_accountMapper;
import cn.com.api.service.ApiT_delivery_account_stateService;
import cn.com.api.service.impl.base.T_delivery_account_stateServiceImplBase;

/**
 * 
 **/
@Service
public class ApiT_delivery_account_stateServiceImpl extends T_delivery_account_stateServiceImplBase implements ApiT_delivery_account_stateService{
	@Autowired
	private ApiT_delivery_account_stateMapper apiT_delivery_account_stateMapper;
	@Autowired
	private ApiT_shipper_accountMapper apiT_shipper_accountMapper;
	
	
	/**  每次登录   存上次状态->离岗状态的时间----查询上次时间，如果是上一天，从0:00开始 */
	@Override
	public void loginChangeState(String u_id,Integer workStatus) {
		/** 修改当前配送状态为离岗状态-每次登录默认为离岗状态     如果之前已是离岗状态则不用重新赋值 */
		//0： 离岗 1：在岗 2：小休
		ApiT_shipper_account shipAccount = apiT_shipper_accountMapper.selectShipperAccountByUid(u_id);
		if(shipAccount!=null && !shipAccount.getWorking_status().equals(workStatus.toString())){
			Integer curr_status = Integer.parseInt(shipAccount.getWorking_status());//插入新纪录的当前状态
			
			shipAccount.setWorking_status(workStatus.toString());
			SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String date = dateFormat.format(new Date());
			shipAccount.setUpdate_time(date);
			
			apiT_shipper_accountMapper.updateT_shipper_account(shipAccount);
			
			/**
			 * 插入登录前状态的持续时间
			 * 先查询当天的最近时间，若查询不到，从0:00开始计算 上一状态的持续时间
			 * 
			 */
			String currDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
			ApiT_delivery_account_state deliveryAccount = apiT_delivery_account_stateMapper.selectRecentlyRecordByDate(u_id, currDate);
			Date recentlyDate = null;
			Date changeDate = new Date();
			//
			try {
				if(deliveryAccount!=null){
					recentlyDate = deliveryAccount.getChange_time();
					curr_status = deliveryAccount.getTo_status();//获取上一状态
				}else{
					recentlyDate = dateFormat.parse(currDate+" 00:00:00");//默认赋值为当天0:00
				}
				//新插入一条状态记录
				ApiT_delivery_account_state deliveryAccountNew = new ApiT_delivery_account_state();
				deliveryAccountNew.setCurr_status(curr_status);
				deliveryAccountNew.setTo_status(workStatus);//离岗--登录默认离岗
			    long nm = 1000 * 60;
				int duration = (int) ((changeDate.getTime()-recentlyDate.getTime())/ nm);
				deliveryAccountNew.setChange_time(changeDate);
				deliveryAccountNew.setDuration(duration);//持续时间
				deliveryAccountNew.setU_id(u_id);
				apiT_delivery_account_stateMapper.insertT_delivery_account_state(deliveryAccountNew);
			} catch (ParseException e) {
				e.printStackTrace();
			}
			
		}
	}
    
	
 
}


